package com.wondertek.poms.pre.controller;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wondertek.poms.common.utils.MyThreadPool;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping(value = "/init/data")
public class ImitateMamController {
	/**
	 *  9500132129  平台:89   cpid：699004
		5500001193  平台:89   cpid：800033
		9500132094  平台:89   cpid：800033
		5500001189  平台:89   cpid：600493
		9500132258  平台:89   cpid：600493
		5500001188  平台:89   cpid：800033
	 */
	@GetMapping("/num/{num}")
	public String num(@PathVariable int num) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	MyThreadPool pool = MyThreadPool.getInstance();
    	ThreadPoolExecutor singlePool = pool.getSinglePool();
        List<CompletableFuture<Void>> futures = IntStream.range(0, num)
        		.mapToObj(i -> CompletableFuture.runAsync(()->{
//        			autoSync("1504479719", "189", null, 1, "800033");
//        			autoSync("5500321138", "189", null, 1, "800033"); // 直播频道
//        			autoSync("5501178235", "189", null, 1, "800033"); // 6
        			autoSync("5501182503", "189", null, 1, "800033"); // 7
//        			autoSync("1504461727", "189", null, 1, "800033"); // 8
        		}, singlePool)
        ).collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
        sw.stop();
        return "time length:" + sw.getTime();
	}
	
	@GetMapping("/{contentIds}")
	public String contentId(@PathVariable String contentIds) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	String[] cids = contentIds.split(",");
    	MyThreadPool pool = MyThreadPool.getInstance();
    	ThreadPoolExecutor singlePool = pool.getSinglePool();
        List<CompletableFuture<Void>> futures = IntStream.range(0, 1)
        		.mapToObj(i -> CompletableFuture.runAsync(()->{
        			for (int j = 0; j < cids.length; j++) {
        				autoSync(cids[j], "189", null, 1, "800033");
					}
        		}, singlePool)
        ).collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
        sw.stop();
        return "time length:" + sw.getTime();
	}
	
	@GetMapping("/{contentId}/{port}")
	public String contentId(@PathVariable String contentId, @PathVariable String port) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	MyThreadPool pool = MyThreadPool.getInstance();
    	ThreadPoolExecutor singlePool = pool.getSinglePool();
        List<CompletableFuture<Void>> futures = IntStream.range(0, 1)
        		.mapToObj(i -> CompletableFuture.runAsync(()->{
        			autoSync(contentId, "189", null, 1, "800033", port);
        		}, singlePool)
        ).collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
        sw.stop();
        return "time length:" + sw.getTime();
	}
	
	public void autoSync(String contentId, String platForm, String updateFields, int oprCode, String cpId) {
		autoSync(contentId, platForm, updateFields, oprCode, cpId, "8605");
	}
	
	public void autoSync(String contentId, String platForm, String updateFields, int oprCode, String cpId, String port) {
		String url = "http://localhost:" + port + "/poms-admin/syncContentNotify";
		httpPost(url, getXml(contentId, platForm, updateFields, oprCode, cpId));
		log.info("url:" + url + "|contentId:" + contentId + "|platForm:" + platForm + "|cpId:" + cpId);
	}
	
	private String getXml(String contentId, String platForm, String updateFields, int oprCode, String cpId) {
		if (cpId == null || !NumberUtil.isNumber(cpId)) cpId = "0";
		String cPath = "/zhengshi/" + contentId.substring(0, 4) + "/" + contentId.substring(4, 7)
			+ "/" + contentId.substring(7, 10);
		String dateStr = FastDateFormat.getInstance("yyyyMMddhhmmss").format(new Date());
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<CMS>");
		sb.append("        <AccessID><![CDATA[" + platForm + "]]></AccessID>");
		sb.append("        <AccessSEQ><![CDATA[1000012015031315114323900239]]></AccessSEQ>");
		sb.append("        <AccessPwd><![CDATA[D022646351048AC0BA397D12DFAFA304]]></AccessPwd>");
		sb.append("        <AccessPlatformType><![CDATA[" + platForm + "]]></AccessPlatformType>");
		sb.append("        <AccessPlatformID><![CDATA[" + platForm + "]]></AccessPlatformID>");
		sb.append("        <Version>1.0</Version>");
		
		/*
		 * sb.append("        <DisPlayFileLists>");
		 * sb.append("        		<DisPlayFile>");
		 * sb.append("        <DpFileID><![CDATA[991000004709]]></DpFileID>"); sb.
		 * append("        <DpFileName><![CDATA[5101042938_S11_sc.jpg]]></DpFileName>");
		 * sb.append("        		</DisPlayFile>");
		 * sb.append("        </DisPlayFileLists>");
		 */
		
		sb.append("        <SvcCont>");
		sb.append("                <ContentID><![CDATA[" + contentId + "]]></ContentID>");
		sb.append("                <CPID><![CDATA[" + cpId + "]]></CPID>");
		sb.append("                <BasePath><![CDATA[" + cPath + "]]></BasePath>");
		sb.append("                <EnableType><![CDATA[7]]></EnableType>");
		sb.append("                <OprCode><![CDATA[" + oprCode + "]]></OprCode>");
		sb.append("                <OprTime><![CDATA[" + dateStr + "]]></OprTime>");
		sb.append("                <Priority><![CDATA[0]]></Priority>");
		sb.append("                <ServType><![CDATA[01]]></ServType>");
		sb.append("                <NeedBC><![CDATA[0]]></NeedBC>");
		sb.append("                <distResult><![CDATA[1]]></distResult>");
		sb.append("                <updateFields><![CDATA[" + updateFields + "]]></updateFields>");
		sb.append("        </SvcCont>");
		sb.append("</CMS>");
		return sb.toString();
	}
	
	public static String httpPost(String url, String xml) {
		PostMethod method = new PostMethod(url);
		HttpClient httpClient = new HttpClient();
		try {
			HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(10000);
			managerParams.setSoTimeout(10000);
			StringRequestEntity entity = new StringRequestEntity(xml, "text/xml", "UTF-8");
			method.setRequestEntity(entity);
			int statusCode = httpClient.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("HttpClient Error==[入参:" + xml + "][statusCode = " + statusCode + "]");
				return "";
			}
			InputStream in = method.getResponseBodyAsStream();
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			char[] b = new char[4096];
			for (int n; (n = isr.read(b)) != -1;) {
				sb.append(new String(b, 0, n));
			}
			String returnStr = sb.toString();
			return returnStr;
		} catch (Exception e) {
			log.error("====poms同步工具类的URL失败======" + xml, e);
		} finally {
			method.releaseConnection();
		}

		return "";
	}
}
